import { insertUserSchema, updateUserSchema } from '@/server/db/validate-schema';
import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';

const inputSchema = z.object({
  name: z.string().max(10).min(3),
  email: z.string().email(),
});

export function GET(request: NextRequest) {
  /* return Response.json({
    a: 'Response',
  }); */

  console.log('cache');
  console.log(cookies().get('a')); // 此时该 api 路由不会被缓存

  /*
  const query = request.nextUrl.searchParams;
  const name = query.get('name');
  const email = query.get('email');
	try {
    const result = inputSchema.parse({ name, email });

    return NextResponse.json({ a: 'NextResponse', result });
  } catch (err: any) {
    console.error(err.message);
    return NextResponse.json({ err: err.message });
  } */

  const query = request.nextUrl.searchParams;
  const name = query.get('name');
  const email = query.get('email');
  const id = query.get('id');
  const result = inputSchema.safeParse({ name, email, id });

  const updateUserSchemaResult = updateUserSchema.safeParse({ name, email, id });
  if (updateUserSchemaResult.success) {
    return NextResponse.json({ a: 'NextResponse', result: updateUserSchemaResult.data });
  } else {
    return NextResponse.json({ err: updateUserSchemaResult.error });
  }

  const createUserSchemaResult = insertUserSchema.safeParse({ name, email, id });
  if (createUserSchemaResult.success) {
    return NextResponse.json({ a: 'NextResponse', result: createUserSchemaResult.data });
  } else {
    return NextResponse.json({ err: createUserSchemaResult.error });
  }

  if (result.success) {
    return NextResponse.json({ a: 'NextResponse', result: result.data });
  } else {
    return NextResponse.json({ err: result.error });
  }
}
